// utils/notification.js

// 发送计划通知给管理员
const sendPlanNotification = (plan) => {
  const db = wx.cloud.database()
  
  // 确保计划数据完整
  if (!plan.planNo) {
    plan.planNo = 'PLAN' + Date.now()
  }
  if (!plan.date) {
    plan.date = new Date().toISOString().split('T')[0]
  }
  
  // 获取所有管理员用户
  return db.collection('users')
    .where({
      role: 'admin'
    })
    .get()
    .then(res => {
      const adminUsers = res.data
      
      if (adminUsers.length === 0) {
        console.log('没有管理员用户，不发送通知')
        return { success: false, message: '没有管理员用户' }
      }
      
      // 为每个管理员创建通知记录
      const notifications = adminUsers.map(admin => ({
        _openid: admin._openid,
        type: 'new_plan',
        title: '新计划通知',
        content: `有新的计划 #${plan.planNo}，请及时处理`,
        planId: plan._id,
        planNo: plan.planNo,
        userName: plan.userName,
        isRead: false,
        createTime: db.serverDate()
      }))
      
      // 批量插入通知记录
      return db.collection('notifications')
        .add({
          data: notifications
        })
        .then(() => {
          console.log('订单通知记录保存成功')
          
          // 尝试发送订阅消息
          return sendSubscribeMessages(plan, adminUsers)
            .then(() => {
              return { success: true, message: '通知发送成功', adminCount: adminUsers.length }
            })
            .catch(err => {
              console.error('发送订阅消息失败:', err)
              return { success: true, message: '通知记录保存成功，订阅消息发送失败', adminCount: adminUsers.length }
            })
        })
    })
    .catch(err => {
      console.error('发送计划通知失败:', err)
      return { success: false, message: '发送通知失败: ' + err.message }
    })
}

// 获取用户的通知列表
const getUserNotifications = () => {
  return new Promise((resolve, reject) => {
    const db = wx.cloud.database()
    
    // 获取当前用户openid
    wx.cloud.callFunction({
      name: 'login',
      data: {}
    }).then(res => {
      const openid = res.result.openid
      
      return db.collection('notifications')
        .where({
          _openid: openid
        })
        .orderBy('createTime', 'desc')
        .get()
    }).then(res => {
      resolve(res.data)
    }).catch(err => {
      console.error('获取通知列表失败:', err)
      reject(err)
    })
  })
}

// 标记通知为已读
const markNotificationAsRead = (notificationId) => {
  const db = wx.cloud.database()
  
  return db.collection('notifications')
    .doc(notificationId)
    .update({
      data: {
        isRead: true,
        readTime: db.serverDate()
      }
    })
}

// 删除通知
const deleteNotification = (notificationId) => {
  const db = wx.cloud.database()
  
  return db.collection('notifications')
    .doc(notificationId)
    .remove()
}

// 获取未读通知数量
const getUnreadCount = () => {
  return new Promise((resolve, reject) => {
    const db = wx.cloud.database()
    
    // 获取当前用户openid
    wx.cloud.callFunction({
      name: 'login',
      data: {}
    }).then(res => {
      const openid = res.result.openid
      
      return db.collection('notifications')
        .where({
          _openid: openid,
          isRead: false
        })
        .count()
    }).then(res => {
      resolve(res.total)
    }).catch(err => {
      console.error('获取未读通知数量失败:', err)
      reject(err)
    })
  })
}

// 发送订阅消息给管理员
const sendSubscribeMessages = (plan, adminUsers) => {
  return new Promise((resolve, reject) => {
    if (!adminUsers || adminUsers.length === 0) {
      console.log('没有管理员用户，不发送订阅消息')
      resolve()
      return
    }
    
    // 为每个管理员发送订阅消息
    const promises = adminUsers.map(admin => {
      return sendSingleSubscribeMessage(plan, admin)
        .catch(err => {
          console.error('发送订阅消息失败:', err)
          return null // 继续处理其他管理员
        })
    })
    
    Promise.all(promises)
      .then(results => {
        const successCount = results.filter(r => r !== null).length
        console.log(`成功发送 ${successCount} 个订阅消息`)
        resolve()
      })
      .catch(err => {
        console.error('发送订阅消息失败:', err)
        resolve() // 即使失败也不影响主流程
      })
  })
}


// 发送单个订阅消息
const sendSingleSubscribeMessage = (plan, admin) => {
  return new Promise((resolve, reject) => {
    // 构建订阅消息数据
    const messageData = {
      template_id: 'new-plan-template', // 需要在微信小程序后台配置
      page: `/pages/order/order?id=${plan._id}`,
      data: {
        character_string1: {
          value: plan.planNo || 'PLAN001'
        },
        date2: {
          value: plan.date || new Date().toISOString().split('T')[0]
        },
        phrase3: {
          value: plan.time === 'breakfast' ? '早餐' : 
                 plan.time === 'lunch' ? '午餐' : '晚餐'
        },
        thing5: {
          value: plan.userName || '用户'
        }
      }
    }
    
    // 请求订阅消息权限
    requestSubscribeMessagePermission(plan, admin)
      .then(() => {
        // 保存消息到数据库供管理员查看
        return saveSubscribeMessageToDatabase(order, admin, messageData)
      })
      .then(() => {
        // 显示提示信息
        wx.showModal({
          title: '计划通知',
          content: `已向管理员 ${admin.nickName} 发送新计划通知 (#${plan.planNo})`,
          showCancel: false,
          success: () => {
            resolve()
          }
        })
      })
      .catch(err => {
        console.error('发送订阅消息失败:', err)
        reject(err)
      })
  })
}

// 请求订阅消息权限
const requestSubscribeMessagePermission = (plan, admin) => {
  return new Promise((resolve, reject) => {
    // 尝试请求订阅消息权限
    wx.requestSubscribeMessage({
      tmplIds: ['new-plan-template'],
      success: (res) => {
        if (res['new-order-template'] === 'accept') {
          // 用户接受了订阅消息，保存订阅记录
          saveUserSubscription(admin._openid, 'new-plan-template')
            .then(() => {
              console.log('用户已接受订阅消息')
              resolve()
            })
            .catch(err => {
              console.error('保存订阅记录失败:', err)
              resolve() // 即使保存失败也继续
            })
        } else {
          console.log('用户拒绝了订阅消息')
          resolve()
        }
      },
      fail: (err) => {
        console.error('请求订阅消息权限失败:', err)
        resolve()
      }
    })
  })
}

// 保存用户订阅记录
const saveUserSubscription = (openid, templateId) => {
  const db = wx.cloud.database()
  
  return db.collection('user_subscriptions').add({
    data: {
      _openid: openid,
      template_id: templateId,
      status: 'accept',
      createTime: db.serverDate(),
      expireTime: new Date(Date.now() + 90 * 24 * 60 * 60 * 1000) // 90天后过期
    }
  })
}

// 管理员订阅消息设置
const setupAdminNotifications = () => {
  return new Promise((resolve, reject) => {
    wx.showModal({
      title: '订阅计划通知',
      content: '是否订阅新计划通知？订阅后将在有新计划时收到微信消息提醒。',
      confirmText: '订阅',
      cancelText: '取消',
      success: (res) => {
        if (res.confirm) {
          // 用户点击订阅
          wx.requestSubscribeMessage({
            tmplIds: ['new-plan-template'],
            success: (subscribeRes) => {
              if (subscribeRes['new-order-template'] === 'accept') {
                // 获取当前用户openid
                wx.cloud.callFunction({
                  name: 'login',
                  data: {}
                }).then(loginRes => {
                  const openid = loginRes.result.openid
                  
                  // 保存订阅记录
                  return saveUserSubscription(openid, 'new-plan-template')
                }).then(() => {
                  wx.showToast({
                    title: '订阅成功',
                    icon: 'success'
                  })
                  resolve()
                }).catch(err => {
                  console.error('保存订阅记录失败:', err)
                  wx.showToast({
                    title: '订阅失败',
                    icon: 'error'
                  })
                  reject(err)
                })
              } else {
                wx.showToast({
                  title: '已取消订阅',
                  icon: 'none'
                })
                resolve()
              }
            },
            fail: (err) => {
              console.error('请求订阅权限失败:', err)
              wx.showToast({
                title: '订阅失败',
                icon: 'error'
              })
              reject(err)
            }
          })
        } else {
          // 用户取消订阅
          wx.showToast({
            title: '已取消订阅',
            icon: 'none'
          })
          resolve()
        }
      },
      fail: (err) => {
        console.error('显示订阅弹窗失败:', err)
        reject(err)
      }
    })
  })
}

// 保存订阅消息到数据库
const saveSubscribeMessageToDatabase = (plan, admin, messageData) => {
  const db = wx.cloud.database()
  
  return db.collection('subscribe_messages').add({
    data: {
      _openid: admin._openid,
      template_id: messageData.template_id,
      page: messageData.page,
      data: messageData.data,
      plan_id: plan._id,
      plan_no: plan.planNo,
      status: 'pending', // pending, sent, failed
      createTime: db.serverDate(),
      sendTime: null
    }
  })
}

// 测试通知功能
const testNotification = () => {
  return new Promise((resolve, reject) => {
    const testPlan = {
      _id: 'test-plan-' + Date.now(),
      planNo: 'TEST' + Date.now(),
      date: new Date().toISOString().split('T')[0],
      time: 'lunch',
      userName: '测试用户',
      dishes: [
        { name: '宫保鸡丁' },
        { name: '米饭' }
      ]
    }
    
    sendPlanNotification(testPlan)
      .then(result => {
        console.log('测试通知结果:', result)
        resolve(result)
      })
      .catch(err => {
        console.error('测试通知失败:', err)
        reject(err)
      })
  })
}

module.exports = {
  sendPlanNotification,
  getUserNotifications,
  markNotificationAsRead,
  deleteNotification,
  getUnreadCount,
  setupAdminNotifications,
  testNotification
}